package com.yangye.picommon.utils;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Method;

/**
 * @author yangye
 * @date 2019/9/23
 */
public class IpUtil {

	public static String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		String[] ips = ip.split(",");
		return "0:0:0:0:0:0:0:1".equals(ips[0])?"127.0.0.1":ips[0];
	}

	public static String getIpFrom(String ip) {
		try {
			String path = "ip2region/ip2region.db";
			String name = "ip2region.db";
			int algorithm = DbSearcher.BTREE_ALGORITHM;
			DbConfig config = new DbConfig();
			File file = FileUtil.inputStreamToFile(new ClassPathResource(path).getInputStream(), name);
			DbSearcher searcher = new DbSearcher(config, file.getPath());
			Method method = null;
			switch (algorithm) {
				case DbSearcher.BTREE_ALGORITHM:
					method = searcher.getClass().getMethod("btreeSearch", String.class);
					break;
				case DbSearcher.BINARY_ALGORITHM:
					method = searcher.getClass().getMethod("binarySearch", String.class);
					break;
				case DbSearcher.MEMORY_ALGORITYM:
					method = searcher.getClass().getMethod("memorySearch", String.class);
					break;
				default:
					method = searcher.getClass().getMethod("memorySearch", String.class);
					break;
			}
			DataBlock dataBlock = null;
			dataBlock = (DataBlock) method.invoke(searcher, ip);
			String address = dataBlock.getRegion().replace("0|","");
			if(address.charAt(address.length()-1) == '|'){
				address = address.substring(0,address.length() - 1);
			}
			return address.equals("内网IP|内网IP")?"内网IP":address;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
}
